﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using BaseLib.Helper;

namespace WebUI.Ashx.App
{
    /// <summary>
    /// MakeImage 的摘要说明
    /// </summary>
    public class MakeImage : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                var reqFile = context.Request.QueryString["f"].ToNull();
                var openFile = !reqFile.StartsWith("http") ? File.OpenRead(context.Server.MapPath(reqFile)) : this.GetHttpFile(reqFile);
                var watermaker = context.Server.MapPath(context.Request.QueryString["logo"].ToNull());
                var method = context.Request.QueryString["method"].ToNull();
                var w = context.Request.QueryString["w"].ToInt(320);
                var h = context.Request.QueryString["h"].ToInt(240);
                var q = context.Request.QueryString["q"].ToInt(100);
                if (method.Compare("x"))
                    Images.CutForCustom(openFile, w, h, q);
                else if (method.Compare("y"))
                    Images.CutForSquare(openFile, w, q);
                else
                    Images.ZoomAuto(openFile, w, h, "贵州文化演艺集团", watermaker);
            }
            catch (Exception)
            {
                Images.CutForCustom(File.OpenRead(context.Server.MapPath("/Images/logo.jpg")), 320, 240, 100);
            }
        }

        private Stream GetHttpFile(string httpfile)
        {
            var req = (HttpWebRequest)WebRequest.Create(httpfile);
            var res = (HttpWebResponse)req.GetResponse();
            return res.GetResponseStream();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}